package com.jinjiafeng.framelibrary.skin;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by jinjiafeng.
 * date:on 18-5-9
 */

public class SkinResource {


    private final String mPackageName;
    private Resources mResources;

    @SuppressLint("PrivateApi")
    SkinResource(Context context, String skinPath) {
        Resources parentRes = context.getResources();
        AssetManager manager = null;
        try {
            manager = AssetManager.class.newInstance();
            Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            method.invoke(manager, skinPath);
        } catch (InstantiationException |
                IllegalAccessException |
                NoSuchMethodException |
                InvocationTargetException e) {
            e.printStackTrace();
        }

        if (manager != null) {
            mResources = new Resources(manager, parentRes.getDisplayMetrics(), parentRes.getConfiguration());
        }

        mPackageName = context.getPackageManager().getPackageArchiveInfo(skinPath, 0).packageName;
    }

    /**
     * 根据资源名称获取图片资源
     *
     * @param resName 资源名称
     * @return 图片资源
     */
    public Drawable getDrawableByName(String resName) {
        int resId = mResources.getIdentifier(resName, "drawable", mPackageName);
        try {
            return mResources.getDrawable(resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据资源名称获取颜色值
     *
     * @param resName 资源名称
     * @return 颜色值
     */
    public ColorStateList getColorByName(String resName) {
        int resId = mResources.getIdentifier(resName, "color", mPackageName);
        try {
            return  mResources.getColorStateList(resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
